package org.study.clickhouse.boot.repository;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author LENOVO
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Repository
public class DmlRepository {
    private final JdbcTemplate jdbcTemplate;

    @Transactional(readOnly = true)
    public List<String> showDatabases() {
        String sql = "show databases";
        List<String> dnNameLlist = jdbcTemplate.query(sql, (rs, rowNum) -> rs.getString(1));
        return dnNameLlist;
    }

    @Transactional(readOnly = true)
    public String showCreateDatabase(String databaseName) {
        String sql = "show create database " + databaseName;
        String createDatabaseSql = jdbcTemplate.queryForObject(sql, String.class);
        return createDatabaseSql;
    }

    @Transactional(readOnly = true)
    public List<String> showTables() {
        String sql = "show tables";
        List<String> tableNameList = jdbcTemplate.query(sql, (rs, rowNum) -> rs.getString(1));
        return tableNameList;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> descTables(String tableName) {
        String sql = "desc " + tableName;
        List<Map<String, Object>> tableNameList = jdbcTemplate.query(sql, (rs, rowNum) -> {
            String name = rs.getString(1);
            String type = rs.getString(2);
            String defaultType = rs.getString(3);
            String defaultExpression = rs.getString(4);
            String comment = rs.getString(5);
            String codecExpression = rs.getString(6);
            String ttlExpression = rs.getString(7);
            // System.out.println(name + ", " + type + ", " + defaultType + ", " + defaultExpression + ", " + comment + ", " + codecExpression + ", " + ttlExpression);
            Map<String, Object> map = new LinkedHashMap<>() {{
                this.put("name", name);
                this.put("type", type);
                this.put("defaultType", defaultType);
                this.put("defaultExpression", defaultExpression);
                this.put("comment", comment);
                this.put("codecExpression", codecExpression);
                this.put("ttlExpression", ttlExpression);
            }};
            return map;
        });
        return tableNameList;
    }

    @Transactional(readOnly = true)
    public String showCreateTable(String tableName) {
        String sql = "show create table " + tableName;
        String createTableSql = jdbcTemplate.queryForObject(sql, String.class);
        return createTableSql;
    }
}